#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/4/29 10:23
# @Author  : Link
# @Site    : 
# @File    : web_view_widget.py
# @Software: PyCharm

from PyQt5.QtCore import QUrl, pyqtSignal, Qt
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage, QWebEngineDownloadItem
from PyQt5.QtWidgets import QFileDialog

from frame.logger_moudle import logger


class MyQWebEngineView(QWebEngineView):
    link_pyqtSignal = pyqtSignal(QUrl)
    new_link_pyqtSignal = pyqtSignal(QUrl)
    new_view_pyqtSignal = pyqtSignal(QWebEngineView)
    new_window_pyqtSignal = pyqtSignal(QWebEngineView)
    title_pyqtSignal = pyqtSignal(int, str)

    def __init__(self):
        super(MyQWebEngineView, self).__init__()
        # Title
        self.page().titleChanged.connect(self.title_emit)
        # 下载请求
        self.page().profile().downloadRequested.connect(self.download)
        # url改变
        self.page().urlChanged.connect(self.link_change)

    def set_zoom_factor(self, e: int) -> None:
        factor = e / 100
        self.setZoomFactor(factor)

    def download(self, item: QWebEngineDownloadItem):
        dir_path, dir_type = QFileDialog.getSaveFileName(self, '选择保存路径', r'down/')
        local = dir_path.rfind('/')
        s_path = dir_path[:local]
        s_file = dir_path[local + 1:]
        item.setDownloadFileName(s_file)
        item.setDownloadDirectory(s_path)
        item.finished.connect(lambda :print("download finished"))
        item.accept()

    def link_change(self, q_url: QUrl):
        logger.info(q_url)
        self.link_pyqtSignal.emit(q_url)

    def title_emit(self, title):
        self.title_pyqtSignal.emit(id(self), title)

    def createWindow(self, QWebEnginePage_WebWindowType) -> QWebEnginePage:
        # https://blog.csdn.net/sersan/article/details/108622695
        if QWebEnginePage_WebWindowType == QWebEnginePage.WebBrowserTab:
            # 新页面
            newWeb = MyQWebEngineView()
            newWeb.setAttribute(Qt.WA_DeleteOnClose, True)
            self.new_view_pyqtSignal.emit(newWeb)
            return newWeb  # 一定要记得return啊 卡了我好久
        if QWebEnginePage_WebWindowType == QWebEnginePage.WebBrowserWindow:
            # 新窗口
            newWeb = MyQWebEngineView()
            newWeb.setAttribute(Qt.WA_DeleteOnClose, True)
            self.new_window_pyqtSignal.emit(newWeb)
            return newWeb  # 一定要记得return啊 卡了我好久

        return super(MyQWebEngineView, self).createWindow(QWebEnginePage_WebWindowType)
